package com.ciwong.epaper.modules.me.ui;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.LogOutUtil;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.SerializableManager;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 加入班级
 *
 * @author sugy
 * @version ciwong v.1.0 2015/9/10 14:14
 * @since ciwong v.1.0
 */
public class JoinClassActivity extends BaseActivity
{
    private EditText codeEt;

    private int jumpType;

    private EApplication application;

    @Override
    protected int setView()
    {
        return R.layout.activity_join_class;
    }

    @Override
    protected void findViews()
    {
        codeEt = (EditText) findViewById(R.id.join_class_et);
    }

    @Override
    protected void preCreate()
    {
        super.preCreate();
        jumpType = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_TYPE,
                IntentValue.JumpToJoinClassType.FROM_CLASS_LIST);
    }

    @Override
    protected void initEvent()
    {
        setRightBtnListener(new ViewOnClickListener()
        {
            @Override
            public void avertRepeatOnClick(View v)
            {
                String applyCode = codeEt.getText().toString().trim();
                if (TextUtils.isEmpty(applyCode))
                {
                    showToastAlert(codeEt.getHint().toString());
                }
                else
                {
                    getClassInfoByApplyCode(applyCode);
                }
            }
        });
    }

    @Override
    protected void init()
    {
        setTitleText("加入班级");
        setRightBtnText("加入");
        application = (EApplication) getApplication();
    }

    @Override
    protected void loadData()
    {

    }

    /**
     * 根据邀请码获取班级信息
     *
     * @param applyCode
     *            邀请码
     */
    private void getClassInfoByApplyCode(final String applyCode)
    {
        MeDao.getInstance().getClassInfoByApplyCode(EApplication.BRAND_ID,
                applyCode, new BaseExtCallBack(JoinClassActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"")
                {


                    @Override
                    public void success(Object data)
                    {
                        Clazz clazz = (Clazz) data;
                        if (clazz != null)
                        {
                            CWDialog dialog = new CWDialog(
                                    JoinClassActivity.this);
                            dialog.setTitle(clazz.getClassName());

                            dialog.setMessage(
                                    clazz.getSchool().getSchoolName());
                            dialog.setPositiveButton(android.R.string.ok,
                                    new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which)
                                {
                                    dialog.dismiss();
                                    joinClass(applyCode);
                                }
                            });
                            dialog.setNegativeButton(android.R.string.cancel,
                                    null);
                            dialog.setCancelable(false);
                            dialog.show();
                        }
                        else
                        {
                            failed(null);
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        super.failed(errorCode, data);
                        hideMiddleProgressBar();
//                        showToastError(String.valueOf(data));
                        DialogUtil.showFailedToastByErrorType(JoinClassActivity.this,data);
                    }

                    @Override
                    public void failed(Object data)
                    {
                        hideMiddleProgressBar();
                        DialogUtil.showFailedToastByErrorType(JoinClassActivity.this,data);
//                        showToastError(R.string.connect_disable);
                    }
                });
    }

    /**
     * 加入班级
     *
     * @param applyCode
     */
    private void joinClass(final String applyCode)
    {

        showMiddleProgressBar(getTitleText());

        MeDao.getInstance().joinClassByApplyCode(EApplication.BRAND_ID,
                applyCode, new BaseExtCallBack(JoinClassActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"")
                {


                    @Override
                    public void success(Object data)
                    {
                        final Clazz clazz = (Clazz) data;
                        if (clazz != null)
                        {

                            hideMiddleProgressBar();
                            showToastSuccess(R.string.join_class_success);
                            refreshClassId(clazz);
                            getNetClassList(clazz);

                            if (jumpType == IntentValue.JumpToJoinClassType.FROM_MY_INFO)
                            {// 来自个人信息界面
                                MeJumpManager.jumpToClassList(
                                        JoinClassActivity.this,
                                        R.string.go_back,IntentValue.JumpToJoinClassType.TYPE_CHECK_CLASS_LIST, 0,null,clazz);
                            }
                            else
                            {
                                setResult(RESULT_OK);
                            }

                            finish();

                        }
                        else
                        {
                            failed(null);
                        }

                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        super.failed(errorCode, data);
                        hideMiddleProgressBar();
                        DialogUtil.showFailedToastByErrorType(JoinClassActivity.this,data);
                    }

                    @Override
                    public void failed(Object data)
                    {
                        hideMiddleProgressBar();
                        DialogUtil.showFailedToastByErrorType(JoinClassActivity.this,data);
//
                    }
                });
    }

    /**
     * 获取网络班级列表
     */
    private void getNetClassList(final Clazz clazz)
    {
        MeDao.getInstance().getClassList(EApplication.BRAND_ID,
                new BaseExtCallBack(JoinClassActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"")
                {

                    @Override
                    public void success(Object data)
                    {
                        // 更新本地班级列表
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST,
                                (Serializable) data);
                        application.setClazzs((List<Clazz>) data);
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        super.failed(errorCode, data);
                        refreshLocalClassList(clazz);
                    }

                    @Override
                    public void failed(Object data)
                    {
                        refreshLocalClassList(clazz);
                    }
                });
    }

    /**
     * 刷新本地保存的班级id
     *
     * @param clazz
     */
    private void refreshClassId(Clazz clazz)
    {
        EApplication application = (EApplication) getBaseApplication();
        Clazz tempClazz = application.getClazz();
        if (tempClazz == null)
        {
            application.setClazz(clazz);
            SerializableManager.getInstance().serialize(
                    SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT,
                    clazz);
        }
    }

    /**
     * 刷新本地缓存的班级
     *
     * @param clazz
     */
    private void refreshLocalClassList(final Clazz clazz)
    {
        SerializableManager.getInstance().deSerialize(
                SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST,
                new BaseCallBack()
                {

                    @Override
                    public void success(Object data)
                    {
                        List<Clazz> clazzs = (List<Clazz>) data;
                        if (clazzs == null)
                        {
                            clazzs = new ArrayList<Clazz>();
                        }
                        if (!clazzs.contains(clazz))
                        {
                            clazzs.add(clazz);
                            // 更新本地班级列表
                            SerializableManager.getInstance().serialize(
                                    SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST,
                                    (Serializable) clazzs);
                            application.setClazzs(clazzs);
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        failed(null);
                    }

                    @Override
                    public void failed(Object data)
                    {
                        List<Clazz> clazzs = new ArrayList<Clazz>();
                        clazzs.add(clazz);
                        // 更新本地班级列表
                        SerializableManager.getInstance().serialize(
                                SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST,
                                (Serializable) clazzs);
                        application.setClazzs(clazzs);
                    }
                });
    }
}
